<?php

defined('BASEPATH') or die('No direct script access allowed');

/**
 * 会员控制器
 * @author  Karson
 * @name    user.php
 * @since   2013-7-21 20:36:35
 */
class User_Controller extends Controller {

    private $type = array('expense' => '收支统计', 'asset' => '资产状况', 'report' => '年度报表');

    function index() {
        check_level();

        $expense_list = array();
        $this->db->query("SELECT * FROM {pre}bill WHERE type='expense' AND user_id='{$this->auth->user_id}' ORDER BY id DESC LIMIT 5", "bi");
        while ($row = $this->db->get_array("bi")) {
            $row['category'] = get_category($row['category_id']);
            if (isset($row['category']['father_id'])) {
                $row['father_category'] = get_category($row['category']['father_id']);
            } else {
                $row['father_category'] = array('id' => 0, 'name' => '未知');
            }
            $row['account'] = get_account($row['account_id']);
            $expense_list[] = $row;
        }
        $this->view->assign("expense_list", $expense_list);

        $real = $budget = array('expense' => array());
        $where = ' AND occurtime >= ' . get_unixtime('month') . ' AND occurtime <=' . get_unixtime('month', 0, 'end');
        $this->db->query("SELECT SUM(amount) AS amounts, category_id FROM {pre}bill
            WHERE type='expense' {$where}
            GROUP BY category_id", 'lii');
        while ($row = $this->db->get_array('lii')) {
            if ($row['category_id'] == '') {
                $real['expense']['all'] = (int) $row['amounts'];
            } else {
                $category = get_category($row['category_id']);
                if ($category && isset($category['father_id'])) {
                    $father_id = $category['father_id'];
                    if (isset($real['expense'][$father_id])) {
                        $real['expense'][$father_id] += (int) $row['amounts'];
                    } else {
                        $real['expense'][$father_id] = (int) $row['amounts'];
                    }
                }
            }
            if ($row['amounts'] == '' && $row['category_id'] == '') {
                $real['expense']['total'] = (int) $row['amounts'];
            }
        }

        $year = (int) date("Y");
        $month = (int) date("m");
        $row = $this->db->one("SELECT `month`, `content` FROM {pre}budget WHERE year='{$year}' AND month='{$month}' AND user_id='{$this->auth->user_id}'");
        if ($row) {
            $content = json_decode($row['content'], true);
            $budget['expense'] = isset($content['expense']) ? $content['expense'] : array();
            $budget['expense']['all'] = array_sum($budget['expense']);
        }

        $this->view->assign("budget", $budget);
        $this->view->assign("real", $real);
        $this->view->assign("startdate", get_unixtime('month', 0, 'begin'));
        $this->view->assign("enddate", get_unixtime('month', 0, 'end'));

        $income = $expense = 0;
        $this->db->query("SELECT SUM(amount) AS amounts,type FROM {pre}bill WHERE user_id='{$this->auth->user_id}' AND type IN ('income','expense') {$where} GROUP BY type");
        while ($row = $this->db->get_array()) {
            if ($row['type'] == 'income') {
                $income = $row['amounts'];
            } else {
                $expense = $row['amounts'];
            }
        }
        $data = array('typelist' => $this->type,);
        $this->db->query("SELECT SUM(balance) AS nums,type FROM {pre}account WHERE user_id='{$this->auth->user_id}' GROUP BY type");
        $asset = array();
        foreach ($this->account->account_type as $k => $v) {
            $asset[$k] = 0;
        }
        while ($row = $this->db->get_array()) {
            $asset[$row['type']] = $row['nums'];
        }

        //资产合计
        $asset['total'] = array_sum($asset) - $asset['credit'];
        $data['show']['asset'] = $asset;
        //债权
        $one = $this->db->one("SELECT SUM(amount) AS amount, SUM(outstanding) AS outstanding FROM {pre}bill WHERE user_id='{$this->auth->user_id}' AND type='borrow' AND category_id='1'");
        $one['total'] = $one['settled'] = $one['amount'] - $one['outstanding'];
        $data['show']['creditor'] = $one;
        //债务
        $one = $this->db->one("SELECT SUM(amount) AS amount, SUM(outstanding) AS outstanding FROM {pre}bill WHERE user_id='{$this->auth->user_id}' AND type='borrow' AND category_id='2'");
        $one['settled'] = $one['amount'] - $one['outstanding'];
        $asset['credit'] = -$asset['credit'];
        $one['total'] = $one['outstanding'] + $asset['credit'];
        $data['show']['debtor'] = $one;
        //合计

        $data['show']['income'] = $income;
        $data['show']['expense'] = $expense;
        $data['out'] = get_category_list('expense');
        $data['notice_list'] = get_notice_list(5);

        render("user/index", $data);
    }

    function visitor() {
        if ($this->auth->login('test', 'YrE2kPM5d', 0)) {
            go("/user/index");
        } else {
            show_message("游客登录失败");
        }
    }

    function profile() {
        check_level();
        $data = array();
        if ($this->form->is_submit()) {
            $row = $this->input->post("row");
            if (isset($row['nickname']) && $row['nickname'] != '') {
                $user = array('nickname' => $row['nickname'], 'gender' => $row['gender']);
                unset($row['nickname'], $row['gender']);
                $user_extension = $row;
                user_basic($user);
                user_extension($user_extension);
                $type = 'success';
                $text = '修改成功';
                $code = 1;
            } else {
                $type = 'error';
                $text = '昵称不能为空';
                $code = 0;
            }
            $data['alert_type'] = $type;
            $data['alert_text'] = $text;
            json_output($code, $text);
        }
        render("user/profile", $data);
    }

    function auth() {
        check_level();
        $data = array();
        if ($this->form->is_submit()) {
            $oldpassword = $this->input->post("oldpassword");
            $newpassword = $this->input->post("newpassword");
            $repassword = $this->input->post("repassword");
            $type = 'error';
            if ($oldpassword) {
                if (md5s($oldpassword) == $this->auth->fields['password']) {
                    if ($newpassword == $repassword) {
                        user_basic(array('password' => md5s($newpassword)));
                        $type = 'success';
                        $text = '修改密码成功,请重新登录账户';
                        $code = 1;
                    } else {
                        $text = '新密码两次输入不相同';
                        $code = 0;
                    }
                } else {
                    $text = '原密码不正确';
                    $code = 0;
                }
            } else {
                $text = '旧密码不能为空';
                $code = 0;
            }
            $data['alert_type'] = $type;
            $data['alert_text'] = $text;
            json_output($code, $text);
        }
        render("user/auth", $data);
    }

    /**
     * 会员登录
     */
    function login() {
        $url = isset($_GET['url']) ? $_GET['url'] : '/user/';
        if ($this->auth->is_login())
            show_message('你已经登录，请不要重复登录', $url, 2000, 'help');
        if ($this->form->is_submit('post')) {
            $username = $this->input->post('username');
            $password = $this->input->post('password');
            $keeptime = $this->input->post('savecookie') == 'on' ? 86400 * 30 : 0;
            $today = get_unixtime('day');
            //统计今天登录失败次数
            $failure = $this->db->one("SELECT COUNT(*) AS num FROM {pre}login_failure WHERE username='{$username}' AND createtime>{$today}");
            if ($failure['num'] >= 50 && $username) {
                $field = is_email($username) ? 'email' : 'username';
                $one = $this->db->one("SELECT * FROM {pre}user WHERE {$field}='{$username}'");
                //根据不同判断来发邮件
                if (is_array($one) && $one['email']) {
                    $data['notice_box'] = "对不起！您已经尝试登录5次，我们已经向您的邮箱发送了一封含有免登录链接的邮件，您可以点击链接进入会员中心修改密码！";
                    if ($failure['num'] == 5) {
                        login_failure($username, $password, "登录超过指定次数");
                        $url = site_url("/user/shortcut/webclient/{$one['id']}/" . md5s($one['id'] . $one['password'], 16) . "/user/profile/auth/", 1);
                        $content = "Hi, {$one['username']}：<br />我们发现您在登录返券网时遇到了困难，点击以下链接可以自动登录并设置新的登录密码。<a href='{$url}'>{$url}</a><br />如果上面的链接无法点击，您也可以复制链接，粘贴到浏览器地址栏内打开。";
                        send_email("Hi, {$one['username']} 返券网免登录确认", $content, $one['email']);
                    }
                } else {
                    $data['notice_box'] = "对不起！系统只允许尝试登录5次！请尝试<a href='/user/findpwd/'>找回密码</a>或与我们取得联系！";
                }
            } else {
                $captcha = isset($_POST['captcha']) ? strtoupper($this->input->post('captcha')) : null;
                if (!is_email($username) && ($username == '' || strlen($username) < 3 || strlen($username) > 16)) {
                    $error = '用户名输入有误';
                }
                if ($password == '' || strlen($password) < 3 || strlen($password) > 16) {
                    $error = '密码输入有误';
                }
                if (!isset($error)) {
                    if (is_email($username)) {
                        $row = $this->db->one("SELECT id,username,email FROM {pre}user WHERE email='{$username}'");
                        if (!is_array($row)) {
                            $error = "您所登录的用户未找到！";
                        } else {
                            $username = $row['username'];
                        }
                    }
                    if (!isset($error)) {
                        if ($this->auth->login($username, $password, $keeptime)) {
                            go($url);
                        } else {
                            $error = $this->auth->error;
                        }
                    }
                }
                if ($username && $password) {
                    $username = $this->input->post('username');
                    login_failure($username, $password, $error);
                }
                $data['notice_box'] = $error;
            }
        }
        $data['url'] = $url;
        $data['title'] = "会员登录";
        $this->view->display("user/login", $data);
    }

    /**
     * 注册新会员
     */
    function register() {
        $url = isset($_GET['url']) ? $_GET['url'] : '/user/';
        if ($this->auth->is_login())
            show_message('你已经登录，请不要重复注册', $url, 2000, 'help');
        if ($this->form->is_submit('post')) {
            $username = $this->input->post('username');
            $password = $this->input->post('password');
            $repassword = $this->input->post('repassword');
            $email = $this->input->post('email');
            if (!is_email($email))
                $error = 'Email格式不正确';
            if ($username == '' || strlen($username) < 3 || strlen($username) > 15)
                $error = '用户名长度必须大于3位,小于15位';
            if ($password == '' || strlen($password) < 3 || strlen($password) > 15 || $password != $repassword)
                $error = '密码输入有误';
            $row = $this->db->one("SELECT id FROM {pre}user WHERE username='{$username}' OR email='{$email}'");
            if (is_array($row))
                $error = '用户名或Email已经存在';
            $time = time();
            $ip = get_ip();
            $referer = $this->cookie->get('referer_url');
            if (!isset($error)) {
                $new_id = $this->auth->register($username, $password, $email);
                if (!isset($error) && is_numeric($new_id) && $new_id > 0) {
                    $needconfirm = false;
                    $notetitle = str_replace('{username}', $username, $this->config['note']['register_title']);
                    $notecontent = str_replace('{username}', $username, $this->config['note']['register_content']);
                    $emailtitle = str_replace('{username}', $username, $this->config['email']['register_title']);
                    $emailcontent = str_replace('{username}', $username, $this->config['email']['register_content']);
                    //如果有找到confirmurl则表示需要邮箱验证
                    if ($this->config['email_confirm'] && $emailcontent && stripos($emailcontent, '{confirmurl}') !== false) {
                        $needconfirm = true;
                        $confirmcode = sha1($new_id . $username);
                        $confirmurl = site_url("user/confirm/active/{$new_id}/{$confirmcode}/", 1);
                        $emailcontent = str_replace('{confirmurl}', $confirmurl, $emailcontent);
                    }
                    //发送欢迎短信、邮件、显示成功信息！
                    if ($notecontent) {
                        send_note($notetitle, $notecontent, $new_id);
                    }
                    if ($emailcontent) {
                        //因速度影响,暂停发送邮件
                        //send_email($emailtitle, $emailcontent, $email);
                    }
                    $this->auth->login($username, $password);
                    invite($new_id);
                    go($url);
                } else {
                    $error = '注册失败！请检查输入的内容是否正确！';
                }
            }
            $data['notice_box'] = $error;
        }
        $data['url'] = $url;
        $data['title'] = "会员注册";
        $this->view->display("user/register", $data);
    }

    /**
     * 注销登录
     */
    function logout() {
        $go = segment(2, '');
        if ($go == 'go_sina_bind') {
            $url = site_url("user/connect/sina_token");
            $text = '<font color=red>新浪微博</font>绑定页面';
        } else if ($go == 'go_tencent_bind') {
            $url = site_url("user/connect/tencent_token");
            $text = '<font color=red>腾讯微博</font>绑定页面';
        } else if ($go == 'go_renren_bind') {
            $url = '/?f=renren';
            $text = '<font color=red>人人网</font>绑定页面';
        } else {
            $url = '/';
            $text = '网站主页';
        }
        //注销本站
        $this->auth->logout();
        success("你已经成功退出，现在转向{$text}!", $url);
    }

    /**
     * 找回密码
     * @param int $step
     */
    function findpwd($step = 0) {
        if ($this->auth->is_login())
            show_message('你已经登录，不能使用找回密码的功能', site_url('user/index'), 2000, 'help');
        if ($step == 0) {
            $data['title'] = "找回密码第一步";
            if ($this->form->is_submit("POST")) {
                $username = $this->input->post('username');
                if (is_email($username)) {
                    $row = $this->db->one("SELECT username FROM {pre}user WHERE email='{$username}'");
                    if (!is_array($row)) {
                        $error = "您所登录的用户未找到！";
                    } else {
                        $username = $row['username'];
                    }
                }
                $row = $this->db->one("SELECT id,username,password,email FROM {pre}user WHERE username='{$username}'");
                if (!is_array($row))
                    $error = '未找到用户，请确认输入的邮件地址是否正确！';
                if (!isset($error)) {
                    $safetime = base64_encode(time());
                    $safecode = md5s($row['id'] . $row['username'] . $row['password'] . $row['email'], 16);
                    $safecode = substr($safetime, 0, 8) . strtoupper($safecode) . substr($safetime, 8, 8);
                    $url = site_url("user/findpwd/{$row['id']}/{$safecode}", 1);
                    $title = "找回您的密码 － 来自 {$this->config['sitename']}";
                    $content = "亲爱的{$row['username']}：<br />&nbsp;&nbsp;&nbsp;&nbsp;您激活了在{$this->config['sitename']}上找回密码的操作，请点击以下链接进行找回密码<br /><a href='{$url}'>{$url}</a><br />";
                    if (send_email($title, $content, $row['email'])) {
                        $error = '邮件发送成功！请查收您的邮箱！然后点击里面的链接地址重设密码！';
                    } else {
                        $error = '找回密码失败！请联系客服进行重设密码！';
                    }
                }
                $data['notice_box'] = $error;
            }

            $this->view->display("user/findpwd1", $data);
        } else {
            $data['title'] = "找回密码第二步";
            $id = segment(2, 0);
            if (!$id)
                error("参数不正确!");
            $row = $this->db->one("SELECT * FROM {pre}user WHERE id='{$id}'");
            if (!is_array($row))
                error("未找到用户！");
            $safecode = segment(3, '');
            $safetime = base64_decode(substr($safecode, 0, 8) . substr($safecode, 24, 8));
            if (!is_numeric($safetime) || time() - $safetime > 86400) {
                error("重置密码链接已经失效！请重起发起请求！", "/user/findpwd/");
            }
            $md5 = substr($safecode, 8, 16);
            if ($md5 != strtoupper(md5s($row['id'] . $row['username'] . $row['password'] . $row['email'], 16))) {
                error("参数不正确，找回密码失败！");
            }
            if ($this->form->is_submit('POST')) {
                $password = $this->input->post('password');
                $repassword = $this->input->post('repassword');
                if ($password == '' || strlen($password) < 3 || strlen($password) > 16 || $password != $repassword)
                    $error = '密码输入有误，请重新输入！';
                $password = md5s($password);
                if ($this->db->simple("UPDATE {pre}user SET password='{$password}' WHERE id={$id}")) {
                    $error = "找回密码成功！请使用您的新密码<a href='/user/login/'>点击这里</a>进行登录！";
                } else {
                    $error = "找回密码失败或密码未做修改！";
                }
                $data['notice_box'] = $error;
            }
            $data['username'] = $row['username'];
            $data['id'] = $id;
            $data['md5'] = $md5;
            $this->view->display("user/findpwd2", $data);
        }
    }

    /**
     * 调整头像
     */
    function face() {
        check_level();
        $data['face_pos'] = $this->auth->fields['face_pos'] == '' ? '0_0_100' : $this->auth->fields['face_pos'];
        $act = segment(2, '');
        $uid = $this->auth->user_id;
        $face_dir = "uploads/face/{$uid}"; //用户头像目录
        $face_temp_src = ROOTPATH . "{$face_dir}/temp.jpg"; //用户上传的头像源图
        $face160_url = "/{$face_dir}/160.jpg" . "?t=" . microtime(); //用户头像地址
        $face160_src = ROOTPATH . "{$face_dir}/160.jpg"; //用户上传的头像源图
        $face_def = '/images/common/face160.gif';
        $this->load->library("image");
        $this->load->library("upload");

        if ($act == 'delete' && $this->auth->fields['face'] != '') {
            @unlink($face_src);
            header("location:/user/face/");
        }
        $img = false;
        if (file_exists($face160_src)) {
            $img = true;
            $this->image->from($face160_src);
            $data['thumb_big_height'] = 50;
            $data['thumb_big_width'] = 50;
            $data['thumb_small_height'] = 30;
            $data['thumb_small_width'] = 30;
            $data['face160'] = $face160_url;
            $data['face160_width'] = $this->image->width;
            $data['face160_height'] = $this->image->height;
        } else {
            $data['face160'] = $this->auth->fields['face160'];
        }

        if ($this->form->is_submit("POST")) {
            if ($act == 'upload') {
                if (!is_dir(ROOTPATH . $face_dir)) {
                    mkdir(ROOTPATH . $face_dir);
                }
                //上传头像，最大2M
                $face_temp = $this->upload->do_upload('avatar', "temp", true, '.jpg,.jpeg,.gif,.png', 2097152, $face_dir);
                if ($face_temp) {
                    $face_temp = ROOTPATH . $face_temp;
                    //将头像保存至源地址
                    $this->image->from($face_temp);
                    if ($this->image->width > 160) {
                        $this->image->resize(160, 0, 0, 0, 0, 0, true);
                    } else {
                        $this->image->resize(0, 0, 0, 0, 0, 0, true);
                    }
                    $this->image->output("jpg", $face160_src, 100);
                    @unlink($face_temp);
                    //$this->db->simple("UPDATE {pre}user SET face='0_0_100' WHERE id='{$this->auth->user_id}'");
                    if (!$img) {
                        scores($this->config['scores']['upload_face'], $this->auth->user_id, '上传头像');
                    }
                    $img = true;
                    $this->image->from($face160_src);
                    $data['thumb_big_height'] = 50;
                    $data['thumb_big_width'] = 50;
                    $data['thumb_small_height'] = 30;
                    $data['thumb_small_width'] = 30;
                    $data['face160'] = $face160_url;
                    $data['face160_width'] = $this->image->width;
                    $data['face160_height'] = $this->image->height;
                    $type = 'success';
                    $text = "头像上传成功！请对图片进行微调，然后点击保存头像设置";
                } else {
                    $type = 'error';
                    $text = $this->upload->files['avatar']['error_msg'];
                }
                go("/user/face/{$type}/");
            } else if ($act == 'thumb' && $img) {
                //开始裁切图片
                $face_pos = $this->input->post("imgpos");
                $pos = explode("_", $face_pos);
                $x1 = $pos[0];
                $y1 = $pos[1];
                $w = $h = $pos[2];
                $face_pos = "{$x1}_{$y1}_{$w}";
                $this->image->resize(50, 50, $x1, $y1, $w, $h, false);
                //保存裁切的图片
                $this->image->output("jpg", ROOTPATH . "{$face_dir}/50.jpg", 100);
                $this->image->from($face160_src);
                $this->image->resize(30, 30, $x1, $y1, $w, $h, false);
                $this->image->output("jpg", ROOTPATH . "{$face_dir}/30.jpg", 100);
                $this->db->simple("UPDATE {pre}user SET face='{$face_pos}' WHERE id='{$uid}'");
                $type = 'success';
                $text = "头像调整成功！";
                $data['face_pos'] = $face_pos;
                json_output(1, $text);
            }
            $data['alert_type'] = $type;
            $data['alert_text'] = $text;
        }
        $data['action'] = segment(2);
        $data['img'] = $img;
        $data['title'] = "修改头像";
        render("user/face", $data);
    }

}